console.log('app.ts')
// 运行时 配置文件
import { getUserInfo } from '@/services'
import { configRoutes } from '@/router/config'
import { PageLoading } from '@ant-design/pro-layout'
import { notification } from 'antd'
import type { RequestConfig, RunTimeLayoutConfig } from 'umi'
import { history, Link } from 'umi'
import RightContent from '@/components/RightContent'
import Footer from '@/components/Footer'
import { BookOutlined, LinkOutlined } from '@ant-design/icons'

const isDev = process.env.NODE_ENV === 'development'
const loginPath = '/login'

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
	loading: <PageLoading />
}

let asyncRoutes: any[] = []

// 1. render函数一般用来请求服务端动态路由
export async function render(oldRender: any) {
	console.log('2. 我是render函数')
	let token = localStorage.getItem('token')

	const result = token ? await getUserInfo({ token }) : null

	console.log('render 请求服务端路由接口:', result)
	const menus = result ? result?.data?.menus : []
	// const { menus } = data
	// const { username } = data;
	const accessedRouters = configRoutes.filter((v) => {
		//admin帐号直接返回所有菜单
		// if(username==='admin') return true;
		if (hasPermission(menus, v)) {
			// 更改一级路由
			v.component = require(`@/layouts` + v.component).default
			// console.log('v:', v.component)
			if (v.routes && v.routes.length > 0) {
				// 更改二级路由
				v.routes = v.routes.filter((child) => {
					if (hasPermission(menus, child)) {
						child.component = require('@/pages' + child.component).default
						return child
					}
					return false
				})
				return v
			} else {
				return v
			}
		}
		return false
	})
	//   // 路由赋值
	asyncRoutes = accessedRouters
	console.log('过滤好的路由:', asyncRoutes)
	oldRender()
}

// // 2. patchRoutes一般用来 对于请求到的数据，进行拼接处理
export function patchRoutes({ routes }: any) {
	console.log('1，我是动态添加路由函数')
	asyncRoutes.forEach((v) => {
		routes.push(v)
	})
	console.log('我是添加后的路由：', routes)
}

// // 1. 前端一份路由 -> 全面的路由   后端一份路由 -> 根据用户登陆身份返回响应路由信息；

// // 2. 前端循环匹配，两份数据，最终，得到跟后端返回路由匹配的前端路由；

// // 3. 将匹配出来前端路由，通过patchRoutes函数添加进入咱们的路由表就可以了；

// //判断是否有权限访问该菜单
function hasPermission(menus: any[], route: any) {
	if (route.name) {
		let currMenu = getMenu(route.name, menus)
		if (currMenu != null) {
			//设置菜单的标题、图标和可见性
			// if (currMenu.title != null && currMenu.title !== '') {
			//   route.meta.title = currMenu.title;
			// }
			// if (currMenu.icon != null && currMenu.title !== '') {
			//   route.meta.icon = currMenu.icon;
			// }
			// if(currMenu.hidden!=null){
			//   route.hidden = currMenu.hidden !== 0;
			// }
			// if (currMenu.sort != null && currMenu.sort !== '') {
			//   route.sort = currMenu.sort;
			// }
			return true
		} else {
			route.sort = 0
			if (route.hidden !== undefined && route.hidden === true) {
				route.sort = -1
				return true
			} else {
				return false
			}
		}
	} else {
		return true
	}
}

//根据路由名称获取菜单
function getMenu(name: any, menus: any) {
	for (let i = 0; i < menus?.length; i++) {
		let menu = menus[i]
		if (name === menu.name) {
			return menu
		}
	}
	return null
}

//对菜单进行排序
function sortRouters(accessedRouters: any) {
	for (let i = 0; i < accessedRouters.length; i++) {
		let router = accessedRouters[i]
		if (router.children && router.children.length > 0) {
			router.children.sort(compare('sort'))
		}
	}
	accessedRouters.sort(compare('sort'))
}

//降序比较函数
function compare(p: any) {
	return function (m: any, n: any) {
		let a = m[p]
		let b = n[p]
		return b - a
	}
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }: any) => {
	return {
		rightContentRender: () => <RightContent />,
		disableContentMargin: false,
		waterMarkProps: {
			content: initialState?.currentUser?.name
		},
		footerRender: () => <Footer />,
		onPageChange: () => {
			const { location } = history
			// 如果没有登录，重定向到 login
			if (!initialState?.currentUser && location.pathname !== loginPath) {
				history.push(loginPath)
			}
		},
		links: isDev
			? [
					<Link to="/umi/plugin/openapi" target="_blank">
						<LinkOutlined />
						<span>OpenAPI 文档</span>
					</Link>,
					<Link to="/~docs">
						<BookOutlined />
						<span>业务组件文档</span>
					</Link>
			  ]
			: [],
		menuHeaderRender: undefined,
		// 自定义 403 页面
		// unAccessible: <div>unAccessible</div>,
		...initialState?.settings
	}
}
